﻿using System.Collections.Generic;
using System.IO;
using System.Net;
using System.Reflection;
using Microsoft.Office.Interop.Outlook;
using Outlook.WorkItems.Extension.Controls;
using System;

namespace Outlook.WorkItems.Extension.Addin.Actions
{
    public class DownloadAttachmentsFromTeamPortalAction : IBowieAction
    {
        private readonly Attachments _attachments;
        public string HtmlLink { get; set; }
        public List<Tuple<string, string>> HtmlLinks { get; set; }

        public DownloadAttachmentsFromTeamPortalAction(Attachments attachments)
        {
            _attachments = attachments;
            HtmlLink = "";
            HtmlLinks = new List<Tuple<string, string>>();
        }

        public void Do()
        {
            using (var frm = new DownloadAttachmentsForm())
            {
                if (frm.ShowDialog() != System.Windows.Forms.DialogResult.OK)
                    return;

                foreach (var document in frm.WssDocumentsToDownload)
                {
                    var filePath = document.Key;
                    var urlFile = filePath;
                    var fileName = filePath.Substring(filePath.LastIndexOf("/") + 1, filePath.Length - (filePath.LastIndexOf("/") + 1));

                    if (frm.InsertAsHtmlLink == false)
                    {
                        var client = new WebClient { UseDefaultCredentials = true };

                        var path = Path.Combine(Path.GetTempPath(), fileName);

                        client.DownloadFile(urlFile, path);

                        _attachments.Add(path, OlAttachmentType.olByValue, Missing.Value, fileName);
                    }
                    else
                    {
                        HtmlLinks.Add(new Tuple<string, string>(fileName, urlFile));
                        HtmlLink += string.Format(@"<a href=""{0}"">{1}</a><br />", urlFile, fileName);
                    }
                }
            }
        }
    }
}
